﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace SponsorshipManager.DataAccess
{
    public class StoredProcedure
    {
        public string Name {get; set;}
        private List<IDataParameter> Parameters { get; set; }
        public DataTable QueryResult { get; private set; }
        public string Token { get; set; }
        internal IDbProvider Provider { get; set; }

        public IDataParameter GetParameter(string Name) 
        {
            /*
            foreach (IDataParameter p in Parameters)
            {
                if (p.ParameterName == Name)
                    return p;
            }
            */
            // try To figure out how to do this with as lambda InvalidExpressionException.
            IDataParameter p = Parameters.Find(x => x.ParameterName == Name);
            return p;

        }

        public void AddParameter(string Name, DbType Type, object Value, ParameterDirection Direction = ParameterDirection.Input)
        {
            IDataParameter Param = Provider.Parameter();
            Param.DbType = Type;
            Param.ParameterName = Name; 
            Param.Direction = Direction;
            Param.Value = Value;
            Parameters.Add(Param);
        }

        public void AddParameter(string Name, DbType Type, ParameterDirection Direction = ParameterDirection.Output)
        {
            IDataParameter Param = Provider.Parameter();
            Param.DbType = Type;
            Param.ParameterName = Name;
            Param.Direction = Direction;
            Parameters.Add(Param);
        }
        

        public int ExecuteNoQuery()
        {
            int ret = 0;
            if (!Provider.Connected)
            {
                Provider.Connected = true;
            }
            ret = Provider.ExecStoredProc(Name, Parameters, Token);
            if (!Provider.PersistConnections)
            {
                Provider.Connected = false;
            }
            return ret;
        }

        public int Execute()
        {
            int ret = 0;
            if (!Provider.Connected)
            {
                Provider.Connected = true;
            }
            DataTable dt;
            ret = Provider.ExecStoredProc(Name, Parameters, out dt, Token);
            QueryResult = dt;
            if (!Provider.PersistConnections)
            {
                Provider.Connected = false;
            }
            return ret;

        }

        internal StoredProcedure(IDbProvider Provider) 
        {
            this.Provider = Provider;
            Parameters= new List<IDataParameter>();
        }
    }
}
